# !/bin/bash
# install erlang from the server

usage()
{
    echo "install_erlang.sh - install the erlang"
    echo "  -f          the erlang otp source archive name, e.g otp_src_R13B02-1.tar.gz."
    echo "  -h          the server ip, store the erlang otp source packet"
    echo ""
    echo "examples:"
    echo " ./install_erlang.sh -f otp_src_R13B02-1.tar.gz  -h 10.22.242.101"
    echo "   copy the otp_src_R13B02-1.tar.gz file from 10.22.242.101 to /root/software"
    echo "   then complie and install: ./configure && make && make install"
}

desc()
{
    echo "--------------------------------------------------"
    echo "this script copy the erlang otp_src from "
    echo "specify server by scp (default is 10.22.241.101)"
    echo "to root/software, then extract the source compile"
    echo "and install the erlang otp"
    echo "--------------------------------------------------"
}

OTP_SRC=""

SOURCE_SERVER="10.22.241.101"
SOURCE_PATH="/root"

LOCAL_PATH="/root/software"
LOCAL_FILE=""


while [ $# -gt 0 ]; 
do
    ARG=$1
    shift
    case $ARG in
        -f )
            OTP_SRC=$1
            shift;;
        -h )
            SOURCE_SERVER=$1
            shift;;
        * ) 
            usage
    esac
done

# check args
if [ -z "$OTP_SRC" ]; then
    echo "please specify the otp source file name"
    usage
    exit 1
fi

if ! mkdir -p $LOCAL_PATH; then
    exit 1
fi

LOCAL_FILE="$LOCAL_PATH"/"$OTP_SRC"
OTP_SRC_BASE=`basename $OTP_SRC .tar.gz`

# copy the otp source
if ! ([ -f "$LOCAL_FILE" ] && [ $(wc -c "$LOCAL_FILE" | cut -d ' ' -f 1) -ge 52428800 ]); then
    if ! scp root@"$SOURCE_SERVER":"$SOURCE_PATH"/"$OTP_SRC" "$LOCAL_FILE" ; then
        echo "copy the $OTP_SRC error!"
        exit 1
    fi
fi

echo extract the packet...

if ! tar xzf $LOCAL_FILE -C $LOCAL_PATH; then
    echo extract $LOCAL_FILE error!
    exit 1
fi

echo configure...
if ! ( cd $LOCAL_PATH/$OTP_SRC_BASE && ./configure && make && make install ) then
    echo "compile error"
    exit 1
fi

